package com.itany.interceptor;


import com.itany.constant.Constant;
import com.itany.pojo.ManagerUser;
import com.itany.vo.Menu;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;


public class LogInterceptor implements HandlerInterceptor {


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws ServletException, IOException {
        String requestURI = request.getRequestURI();

        System.out.println("---> 拦截器工作中, 请求url为：" + requestURI);

        Object loginaAttribute = request.getSession().getAttribute(Constant.LOGIN_USER_KEY);

        Menu requestMenu = new Menu();
        requestMenu.setUrl(requestURI);

        if (loginaAttribute == null) {

            response.sendRedirect("/manager/showlogin");
            return false;
        } else {
            String referer = request.getHeader("Referer");
            if (referer == null) {
                response.sendRedirect("/manager/showerror");
                return false;
            }
            //获取Referer的uri,如果发起者页面通过，则发起者页面的任意请求都通过
            String refererUri = URI.create(referer).getPath();
            System.out.println("refererUri:" + refererUri);
            Menu refererMenu = new Menu();
            refererMenu.setUrl(refererUri);
            if (Constant.PASS_AFTER_LOGIN.contains(requestURI)) {
                return true;
            }
            Object menuAttribute = request.getSession().getAttribute(Constant.MENU_KEY);
            if (!(menuAttribute instanceof List<?>)) {
                return false;
            }
            List<Menu> menus = new ArrayList<>();

                for (Object o : (List<?>) menuAttribute) {
                    if (!(o instanceof Menu)) {
                        return false;
                    }
                    menus.add((Menu) o);
                }

            for (Menu menu : menus) {
                if (menu.getMenus().contains(requestMenu) || menu.getMenus().contains(refererMenu)) {
                    return true;
                }
            }
            return false;

        }
    }

}
